package GoodsService

import (
	"context"
	"errors"
	"gdshop-admin-go-api/app/request/BaseReq"
	"gdshop-admin-go-api/app/request/GoodsReq"
	"gdshop-admin-go-api/library/response"
	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/util/gconv"
	"strings"
	"time"
)

func SaveGoods(r *ghttp.Request, req *BaseReq.I, parames *GoodsReq.Update) *response.JsonResponse {
	ctx := r.GetCtx()
	//data := r.GetMap()
	// 修改时间
	//data["update_at"] = time.Now().Unix()
	// 增加附加数据

	// 删除更新时不需要的字段
	/*delete(data, "id")
	delete(data, "type")
	delete(data, "cates")
	delete(data, "sales")
	delete(data, "min_price")
	delete(data, "max_price")
	delete(data, "stock")
	delete(data, "stock_cnf")
	delete(data, "create_at")
	delete(data, "delete_at")*/

	err := g.DB().Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
		goodsData := g.Map{
			"goods_name":    parames.GoodsName,
			"unit":          parames.Unit,
			"sub_title":     parames.SubTitle,
			"short_title":   parames.ShortTitle,
			"cates":         "," + gconv.String(parames.CategoryId) + ",",
			"display_sort":  parames.DisplaySort,
			"cover":         parames.Cover,
			"video_url":     parames.VideoUrl,
			"virtual_sales": parames.VirtualSales,
			"is_show_sales": getCheckAttrs(parames.CheckAttrs, "is_show_sales"),
			"is_show_stock": getCheckAttrs(parames.CheckAttrs, "is_show_stock"),
			"is_recommand":  getCheckAttrs(parames.CheckAttrs, "is_recommand"),
			"is_new":        getCheckAttrs(parames.CheckAttrs, "is_new"),
			"is_hot":        getCheckAttrs(parames.CheckAttrs, "is_hot"),
			"spu":           parames.Spu,
			"update_at":     time.Now().Unix(),
		}
		var err error
		goodsId := gconv.Int(req.Id)
		if goodsId > 0 {
			goodsData["update_at"] = time.Now().Unix()
			_, err = tx.Model("goods").Where("id",
				req.Id).Unscoped().Update(goodsData)
			if err != nil {
				return errors.New("goods Update err " + err.Error())
			}
		} else {
			goodsData["create_at"] = time.Now().Unix()
			id, err := tx.Model("goods").Unscoped().InsertAndGetId(goodsData)
			if err != nil {
				return errors.New("goods Insert err " + err.Error())
			}
			goodsId = gconv.Int(id)
		}
		// 更新 goods_extend
		err = saveGoodsExtendByTx(tx, g.Map{
			"goods_id":             goodsId,
			"goods_thumbs":         strings.Join(parames.Thumbs, ","),
			"goods_content":        parames.Content,
			"goods_mobile_content": parames.MobileContent,
		})
		if err != nil {
			return errors.New("goods_extend err " + err.Error())
		}
		// 更新 goods_spec goods_spec_item goods_option
		err = saveGoodsSpecsByTx(tx, goodsId, parames.Specs, parames.SpecTables)
		if err != nil {
			return errors.New("goods spec err " + err.Error())
		}

		err = saveGoodsAttribute(tx, goodsId, parames.Attributes)
		if err != nil {
			return err
		}

		return nil
	})
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}

	return response.SuccessByRequestMessage(nil, "编辑成功")
}

func saveGoodsAttribute(tx *gdb.TX, goodsId int, attributeDatas []*GoodsReq.GoodsAttributes) error {
	_, err := tx.Model("goods_attribute").Where("goods_id", goodsId).
		Where("attribute_type", 1).Delete()
	if err != nil {
		return err
	}

	for _, item := range attributeDatas {
		_, err := tx.Model("goods_attribute").InsertAndGetId(g.Map{
			"goods_id":       goodsId,
			"attribute_type": 1,
			"icon_name":      item.IconName,
			"icon_text":      item.IconText,
		})
		if err != nil {
			return err
		}
	}

	return nil
}
